/*
 *  Developer module js in here
 *  the first time use OOP js
 */

function Developer() {
    this.initial();
}

Developer.prototype = {
    version:"0.1",
    initial:function () {
        this.toggleMenu();
        this.initialConfirmModal();
    },
    toggleMenu:function () {
        var href = location.href;

        $("#mainMenu li").removeClass("active");
        if (href.indexOf("sprint_") > 0) {
            $("#mainMenu li:eq(1)").addClass("active");
        } else if (href.indexOf("backlog_") > 0) {
            $("#mainMenu li:eq(2)").addClass("active");
        } else if (href.indexOf("project_") > 0) {
            $("#mainMenu li:eq(3)").addClass("active");
        } else {
            $("#mainMenu li:eq(0)").addClass("active");
        }
    },
    initialConfirmModal:function () {
        var self = this;
        $(".confirm").click(function (event) {
            event.preventDefault();
            var $this = $(this);
            var title = self.checkEmptyText($this.attr("confirm-title"), "Confirm");
            var content = self.checkEmptyText($this.attr("confirm-content"), "Are you sure ?");
            var url = self.checkEmptyText($this.attr("href"), $this.attr("url"));

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html(title);
            $modal.find(".modal-body p").html(content);
            //add click event
            $modal.find("#confirmModalBtn").show().one("click", function (event) {
                event.preventDefault();
                location.href = url;
            });
            $modal.modal("show");
        });
    },
    initialTooltips:function (ele) {
        $(ele || "span[title],a[title],div[title]").tooltip({
            placement:'bottom',
            html:true,
            delay:100
        });
    },
    checkEmptyText:function (origText, defaultText) {
        if (origText == null || $.trim(origText) == '') {
            return defaultText;
        }
        return origText;
    },
    initialAlert:function (eleId, fadeInTime, fadeOutTime) {
        if ('' != eleId) {
            fadeInTime = fadeInTime || 1000;     //default fade in: 1000ms
            fadeOutTime = fadeOutTime || 1000; //default fade out: 1000ms
            var $alert = $("#" + eleId);
            $alert.show().parent().parent().fadeIn(fadeInTime).slideUp(fadeOutTime);
        }
    }
};

/*
 *  developer_home.jsp
 */

function DeveloperHome(alertEleId) {
    this.initialEvents();
    Developer.prototype.initialAlert(alertEleId);
}
DeveloperHome.prototype = new Developer();

DeveloperHome.prototype = {
    initialChart:function (labels, expectDatas, actualDatas, steps, stepWidth) {
        var data = {
            labels:labels,
            datasets:[
                {
                    fillColor:"rgba(255,255,255,0.5)",
                    strokeColor:"rgba(0,0,255,0.8)",
                    pointColor:"rgba(0,0,255,0.8)",
                    pointStrokeColor:"#fff",
                    data:expectDatas
                },
                {
                    fillColor:"rgba(151,187,205,0.4)",
                    strokeColor:"rgba(255,0,0,0.8)",
                    pointColor:"rgba(255,0,0,0.8)",
                    pointStrokeColor:"#fff",
                    data:actualDatas
                }
            ]
        };
        $("#burnDownChart").attr("height", 150).attr("width", 220);
        var context = $("#burnDownChart").get(0).getContext("2d");
        new Chart(context).Line(data, {
            scaleOverride:true,
            scaleStepWidth:stepWidth,
            scaleStartValue:0,
            scaleSteps:steps
        });
    },
    initialEvents:function () {
        this.initialSprintChange();
        this.initialTaskTab();
        this.initialTaskClasses();

        Developer.prototype.initialTooltips();
        this.initialPopovers();
        this.finishTaskEvent();

        this.startSprintEvent();
        this.finishSprintEvent();
        this.showBacklogEvent();

        this.burnDownDetailsEvent();
        this.meetingFormEvent();
        this.initialSprintMeetingDetails();

        this.moveTaskEvent();
    },
    initialSprintMeetingDetails:function () {
        $("a.taskMeetingDetails").click(function () {
            var loadUrl = $(this).attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Sprint meeting details");
            $modal.find(".modal-body p").load(loadUrl, function () {
                $modal.find("#confirmModalBtn").hide();
                $modal.modal("show");
            });
        });
    },
    moveTaskEvent:function () {
        var self = this;
        $("a.moveTask").click(function () {
            var loadUrl = $(this).attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Move task");
            $modal.find(".modal-body p").load(loadUrl, function () {
                $modal.find("#confirmModalBtn").show().click(function () {
                    if (self._validateMoveTaskTargetSprint()) {
                        $("#moveTaskForm").submit();
                    }
                });
                $modal.modal("show");
            });
        });
    },
    _validateMoveTaskTargetSprint:function () {
        var targetSprintGuid = $("#moveTaskForm #targetSprintSelect").val();
        if ("" == targetSprintGuid) {
            $("#targetSprintSelectError").show();
            return false;
        }
        return true;
    },
    burnDownDetailsEvent:function () {
        $("#burnDownDetailsId").click(function () {
            var loadUrl = $(this).attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Burn down details");
            $modal.find(".modal-body p").load(loadUrl, function () {
                $modal.find("#confirmModalBtn").hide();
                $modal.modal("show");
            });
        });
    },
    meetingFormEvent:function () {
        var self = this;
        $("#meetingFormId").click(function () {
            var loadUrl = $(this).attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Sprint meeting");
            $modal.find(".modal-body p").load(loadUrl, function () {
                $modal.find("#confirmModalBtn").show().bind("click", function () {
                    if (!self._validateMeetingForm()) {
                        $("#sprintMeetingForm").submit();
                    }
                });
                $modal.modal("show");
            });
        });
    },
    _validateMeetingForm:function () {
        var editor = CKEDITOR.instances.content;
        var text = editor.getData();
        var empty_ = (text == "" || $.trim(text) == "");
        if (empty_) {
            $("span#meetingContentWarn").show();
        }
        return empty_;
    },
    showBacklogEvent:function () {
        $(".taskBacklogDetail").click(function () {
            var loadUrl = $(this).attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Backlog");
            $modal.find(".modal-body p").load(loadUrl, function () {
                $modal.find("#confirmModalBtn").hide();
                $modal.modal("show");
            });
        });
    },
    startSprintEvent:function () {
        $("a.startSprint").click(function (event) {
            event.preventDefault();
            var $this = $(this);
            var url = $this.attr("href");
            var loadUrl = $this.attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Start sprint");
            $modal.find(".modal-body p").load(loadUrl, function () {
                $modal.find("#confirmModalBtn").show().one("click", function (event) {
                    event.preventDefault();
                    if ('true' == $("#checkSprintStartPass").val()) {
                        location.href = url;
                    } else {
                        location.href = $("a.editSprintClass").attr("href");
                    }
                });
                $modal.modal("show");
            });

        });
    },
    finishSprintEvent:function () {
        $("a.finishSprint").click(function (event) {
            event.preventDefault();
            var $this = $(this);
            var url = $this.attr("href");
            var loadUrl = $this.attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Finish sprint");
            $modal.find(".modal-body p").load(loadUrl, function () {
                //check finish or not
                var allowFinish = $("#checkSprintAllowFinish").val();
                if ('true' == allowFinish) {
                    $modal.find("#confirmModalBtn").show().one("click", function (event) {
                        event.preventDefault();
                        location.href = url;
                    });
                } else {
                    $modal.find("#confirmModalBtn").hide();
                }
                $modal.modal("show");
            });
        });
    },
    finishTaskEvent:function () {
        $("a.finishTask").click(function (event) {
            event.preventDefault();
            var $this = $(this);
            var url = $this.attr("href");
            var loadUrl = $this.attr("load-url");
            var title = $this.attr("modal-title");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html(title);
            $modal.find(".modal-body p").load(loadUrl, function () {
                //add click event
                $modal.find("#confirmModalBtn").show().one("click", function (event) {
                    event.preventDefault();
                    location.href = url + "?usedTime=" + $("#actualUsedTimeSelect").val();
                });
                $modal.modal("show");
            });
        });
    },
    initialPopovers:function () {
        $("#sprintInfo").popover({
            html:true,
            delay:200,
            title:"Sprint details"
        });

        $("span.taskDetails").popover({
            html:true,
            delay:200,
            placement:'left',
            title:"Task details"
        });
    },
    initialTaskClasses:function () {
        $("table#task .urgent").parent().addClass("error");
        $("table#task .FINISHED").parent().addClass("success");
        $("table#task .CANCELED").parent().addClass("warning");
        $("table#task .PENDING").parent().addClass("info");
    },
    initialTaskTab:function () {
        $(".taskTab").click(function (event) {
            event.preventDefault();
            $("input#taskStatus").val($(this).attr("task-status"));
            $("#developerForm").submit();
        });
    },
    initialSprintChange:function () {
        $("#sprintSelect").change(function () {
            this.form.submit();
        });
    }
};

/*
 *  sprint_form.jsp
 */
function SprintForm() {
    this.initialEvents();
}
SprintForm.prototype = new Developer();

SprintForm.prototype = {
    initialEvents:function () {
        this.changeAddTaskEvent();
        this.initialBudgetBacklogTimes();
    },
    initialBudgetBacklogTimes:function () {
        var self = this;
        $("#backlogUl li input:checkbox").click(function () {
            var $this = $(this);
            if ($this.attr("checked")) {
                $this.parent().find(".estimateTime").addClass("backlogEstTime");
            } else {
                $this.parent().find(".estimateTime").removeClass("backlogEstTime");
            }
            self._showBudgetBacklogTimes();
        });
    },
    _showBudgetBacklogTimes:function () {
        var total = 0;
        $("#backlogUl li .backlogEstTime").each(function () {
            total += parseInt($.trim($(this).html()));
        });
        $("#budgetTimes strong").html(total);
    },
    changeAddTaskEvent:function () {
        $("button[type='submit']").click(function () {
            $("#addTask").val($(this).attr("addTask"));
        });
    },
    initialDatePicker:function (startDate) {
        $('#startDate,#deadline').datepicker({
            format:'yyyy-mm-dd',
            autoclose:true,
            startDate:startDate,
            weekStart:1
        });
    }
};

/*
 *  backlog_form.jsp
 */
function BacklogForm(alertEleId) {
    this.initialEvents();
    Developer.prototype.initialAlert(alertEleId);
}
BacklogForm.prototype = new Developer();

BacklogForm.prototype = {
    initialEvents:function () {
        this.changeAddTaskEvent();
    },
    changeAddTaskEvent:function () {
        $("button[type='submit']").click(function () {
            $("#addNext").val($(this).attr("addNext"));
        });
    }
};

/*
 *  sprint_task_form.jsp
 */
function SprintTaskForm(alertEleId) {
    this.initialEvents();
    Developer.prototype.initialAlert(alertEleId);
}
SprintTaskForm.prototype = new Developer();

SprintTaskForm.prototype = {
    initialEvents:function () {
        this.changeAddTaskEvent();
    },
    changeAddTaskEvent:function () {
        $("button[type='submit']").click(function () {
            $("#addNext").val($(this).attr("addNext"));
        });
    }
};

/*
 *  backlog_overview.jsp
 */
function BacklogOverview(alertEleId) {
    this.initialEvents();
    Developer.prototype.initialAlert(alertEleId);
    Developer.prototype.initialTooltips();
}
BacklogOverview.prototype = new Developer();

BacklogOverview.prototype = {
    initialPopovers:function () {
        $(".backlogDetails").popover({
            html:true,
            delay:200,
            placement:'left',
            title:"Backlog details"
        });
    }, initialBacklogClasses:function () {
        $("table#backlog .HIGH").parent().addClass("error");
    }, initialEvents:function () {
        this.initialPopovers();
        this.initialBacklogClasses();
    }
};


/*
 *  sprint_overview.jsp
 */
function SprintOverview(alertEleId) {
    this.initialEvents();
    Developer.prototype.initialAlert(alertEleId);
}
SprintOverview.prototype = new Developer();

SprintOverview.prototype = {
    initialPopovers:function () {
        $(".sprintDetails").popover({
            html:true,
            delay:200,
            placement:'left',
            title:"Sprint details"
        });
    },
    showBacklogEvent:function () {
        $(".sprintBacklogDetails").click(function () {
            var loadUrl = $(this).attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Sprint backlogs");
            $modal.find(".modal-body p").load(loadUrl, function () {
                $modal.modal("show");
                $modal.find("#confirmModalBtn").hide();
            });

        });
    },
    startSprintEvent:function () {
        $("a.startSprint").click(function (event) {
            event.preventDefault();
            var $this = $(this);
            var url = $this.attr("href");
            var loadUrl = $this.attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Start sprint");
            $modal.find(".modal-body p").load(loadUrl, function () {
                //add click event
                $modal.find("#confirmModalBtn").one("click", function (event) {
                    event.preventDefault();
                    if ('true' == $("#checkSprintStartPass").val()) {
                        location.href = url;
                    } else {
                        location.href = $("a.editSprintClass").attr("href");
                    }
                });
                $modal.modal("show");
            });
        });
    },
    finishSprintEvent:function () {
        $("a.finishSprint").click(function (event) {
            event.preventDefault();
            var $this = $(this);
            var url = $this.attr("href");
            var loadUrl = $this.attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Finish sprint");
            $modal.find(".modal-body p").load(loadUrl, function () {
                //check finish or not
                var allowFinish = $("#checkSprintAllowFinish").val();
                if ('true' == allowFinish) {
                    $modal.find("#confirmModalBtn").one("click", function (event) {
                        event.preventDefault();
                        location.href = url;
                    });
                } else {
                    $modal.find("#confirmModalBtn").hide();
                }
            });
            $modal.modal("show");
        });
    },
    statusChangeEvent:function () {
        $("#sprintStatusSelect").change(function () {
            $("#sprintForm").submit();
        });
    },
    initialSprintClasses:function () {
        $("table#sprint .FINISHED").parent().addClass("success");
        $("table#sprint .PENDING").parent().addClass("info");
    },
    initialEvents:function () {
        this.initialPopovers();
        this.statusChangeEvent();
        this.initialSprintClasses();
        this.showBacklogEvent();

        this.startSprintEvent();
        this.finishSprintEvent();
        Developer.prototype.initialTooltips();
    }
};

/*
 *  sprint_meeting_overview.jsp
 */
function SprintMeetingOverview(alertEleId) {
    this.initialEvents();
    Developer.prototype.initialAlert(alertEleId);
    Developer.prototype.initialTooltips();
}
SprintMeetingOverview.prototype = new Developer();

SprintMeetingOverview.prototype = {
    initialEvents:function () {
        this.addMeetingForm();
        this.initialTypeClass();

        this.editMeetingEvent();
        this.meetingDetailsEvent();
    },
    meetingDetailsEvent:function () {
        $("a.meetingDetails").click(function () {
            var loadUrl = $(this).attr("load-url");

            var $modal = $("#developerModal");
            $modal.find("#developerModalLabel").html("Sprint meeting details");
            $modal.find(".modal-body p").load(loadUrl, function () {
                $modal.find("#confirmModalBtn").hide();
                $modal.modal("show");
            });
        });
    },
    editMeetingEvent:function () {
        var self = this;
        $("a.meetingEdit").click(function () {
            var loadUrl = $(this).attr("load-url");
            self._meetingForm(loadUrl);
        });
    },
    initialTypeClass:function () {
        $("table#meeting .DAILY_STANDING").parent().addClass("info");
        $("table#meeting .SPRINT_REVIEW").parent().addClass("success");
        $("table#meeting .SPRINT_PLANNING").parent().addClass("warning");
    },
    addMeetingForm:function () {
        var self = this;
        $("#sprintMeetingFormId").click(function () {
            var loadUrl = $(this).attr("load-url");
            self._meetingForm(loadUrl);
        });
    },
    _meetingForm:function (loadUrl) {
        var self = this;
        var $modal = $("#developerModal");
        $modal.find("#developerModalLabel").html("Sprint meeting");
        $modal.find(".modal-body p").load(loadUrl, function () {
            $("input#meetingBackToOverview").val(true);
            $modal.find("#confirmModalBtn").show().bind("click", function () {
                if (!self._validateMeetingForm()) {
                    $("#sprintMeetingForm").submit();
                }
            });
            $modal.modal("show");
        });
    },
    _validateMeetingForm:function () {
        var editor = CKEDITOR.instances.content;
        var text = editor.getData();
        var empty_ = (text == "" || $.trim(text) == "");
        if (empty_) {
            $("span#meetingContentWarn").show();
        }
        return empty_;
    }
};

//------------------------------------------------------------------------------------

/**
 * displaytag paginated use  it.
 * Don't change it
 *
 * @param formId
 * @param data
 */
function displaytagform(formId, data) {
    var params = '?';
    $.map(data, function (d) {
        params += (d.f + "=" + d.v + "&");
    });
    var $form = $("#" + formId);
    var action = $form.attr("action");
    var url = action + params;
    var $targetDiv = $form.parent().find(".displayTarget");
    if ($targetDiv.length > 0) {
        //if exist, load  the content to the div
        $targetDiv.load(url);
    } else {
        location.href = url;
    }
}

/*
 *  Call initial js
 * */

$(function () {
    new Developer();
});